require 'amatch'
include Amatch
class Document < ActiveRecord::Base
  belongs_to :section

  # For indexing with solr
  acts_as_solr :facets => [:section_id], :auto_commit=>false,
                :additional_fields=>[{:collection_id=>:integer}, {:sections_id=>:integer}],
        :exclude_fields=>[:type, :created_at, :updated_at, :section_id]

  has_many :document_corrections

  # Returns the collection in which this document resides
  def collection
    section.collection
  end

  # Returns an array of all parent sections (lineage) of this document
  # First item is the root section. Second item is the subsection ... etc.
  def sections
    lineage = []
    s = section
    while s do
      lineage = [s] + lineage
      s = s.parent
    end
    lineage
  end

  # Returns the id for the collection of this document (to be indexed)
  def collection_id
    collection.id
  end

  # Returns the ids of the parent sections of this document (to be indexed)
  def sections_id
    sections.collect {|s| s.id}
  end

  def snippet
    text = body||rewaya||description||''
    words = text.split ' '
    words.size < 12 ? text : (words[0,12].join(' ') + "...")
  end

  def title
    # Should be defined in subclasses
  end
  
  def aya?
    false
  end
  
  def hadith?
    false
  end

  def self.highlight(docs, query)
    results = Hash.new('...')
    m = LongestSubsequence.new(query)
    logger.info query
    docs.each do |doc|
      if doc
        text = doc.body||doc.rewaya||doc.description||''
        best_score = 0
        best_fragment = 0
        fragments = text.split.in_groups_of(10, false).map{|words| words.join ' '}
        fragments.each_with_index do |fragment, i|
          fragment_score = m.match(fragment)
          if fragment_score > best_score
            best_score = fragment_score
            best_fragment = i
          end
        end
        results[doc] = (best_fragment > 0 ? "... " : "") +
          fragments[best_fragment] +
          (best_fragment < fragments.size-1 ? " ..." : "")
      end
    end
    results
  end

#  def self.search(query, options={})
#    logger.info(%(Searching for query: "#{query}"))
#    options[:page] ||= 1
#    options[:results_per_page]||=SolrPaginationExtender::ResultsPerPage
#    options[:page] = options[:page].to_i
#    search_results = Document.find_by_solr(query,
#      :offset=>(options[:page]-1)*options[:results_per_page],
#      :limit=>options[:results_per_page]) # search and return results
#    search_results.extend(::SolrPaginationExtender)
#    return search_results
#  end

  def self.make_better(search_string)
    return search_string if search_string =~ /[\x21-\x7f]/
    words = search_string.split(/ +/)
    search_phrases = words.dup
    1.upto(words.length-1) do |d|
      0.upto(words.length-d-1) do |i|
        search_phrases << %("#{words[i]} #{words[i+d]}"~10)
        break if search_phrases.length > 20
      end
    end
    all_required = words.length <= 3
    better_query = search_phrases.join(all_required ? " && " : " || ")
    better_query = %Q<"#{search_string}" || (#{better_query})>
  end
end

